package com.qf.dao.impl;

import com.qf.dao.ProjectDao;
import com.qf.pojo.Project;
import com.qf.pojo.Stage;
import com.qf.pojo.Developer;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;

public class ProjectDaoImpl implements ProjectDao {
    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {

        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public void addProject(Project project) {
        int i = jdbcTemplate.update("insert into project values(?,?,?,?,?,?,?,?)", project.getPid(), project.getPname(), project.getStarttime(), project.getEndtime(), project.getDid(), project.getCid(), project.getUpdatetime(),project.getStatus());
    }

    @Override
    public void deleteProject(int pid) {
        int i = jdbcTemplate.update("delete from project where pid=?", pid);
        int i1 = jdbcTemplate.update("update stage set pid=0 where pid=?", pid);
    }

    public List<Project> findAll() {
        List<Project> projects = jdbcTemplate.query("select * from project p,developer d where d.did=p.pid", new BeanPropertyRowMapper<>(Project.class));
        for (Project project:projects) {
            String did = project.getDid();
            List<Developer> developers = jdbcTemplate.query("select * from developer where did=?", new BeanPropertyRowMapper<>(Developer.class), did);
            if (developers.size()>0){
                project.setDeveloper(developers.get(0));
            }
            List<Stage> stages = jdbcTemplate.query("select * from stage where pid=?", new BeanPropertyRowMapper<>(Stage.class), project.getPid());
            project.setStages(stages);
        }
        return projects;
    }
}
